
import React, { useState,useEffect,useRef,createContext,useContext,useMemo, useCallback } from 'react';
import reactDom from 'react-dom';
import {Button,Input} from '@material-ui/core'

 const MyContext = createContext();

 const ChildContext = () =>{
   let count = useContext(MyContext)
   return (
     <h3>我是子组件{count}</h3>
   )
 }
//利用context进行参数的传递
const FatherContext = ()=>{
   let [count,setCount] = useState(0);
   const inputEl = useRef(null);

   return (
     <>
     <MyContext.Provider value={count}>
       <ChildContext>

       </ChildContext>

     </MyContext.Provider>
     <Input 
      type="text"
      inputRef={inputEl}
    >

      </Input>
      <p></p>
     <Button 
     variant="contained"
    
     color="primary"
     onClick={()=>{setCount(inputEl.current.value)}}>传递</Button>
     </>

   )
 }
//控制组件更新
 const Memotest =() =>{

   let [count,setCount] = useState(0)
   let [num,setNum] = useState(0)
//count的值改变但组件不进行更新
//num的值改变组件更新
   let res =  useMemo(()=>{
   return {count,num};
   },[num]);

  // let req = useMemo(()=>{
  //   return num
  // });
   return (
     <>
     <h3>父组件状态=count{res.count}/num{res.num}</h3>
     <Button
     variant='contained'
     color="primary"
     onClick={()=>{
       setCount(count+1)
       //查看count的值
       console.log('count:'+count)
     }}>改变count的值</Button>
     <p></p>
    <Button
     variant='contained'
     color="primary"
     onClick={()=>{
       setNum(num+1)
       //查看num的值
       //组件更新时，count也会更新
       console.log('num:'+num)
     }}>改变num的值</Button>
     </>
   )

 }

 const Callbacktest =()=>{
  let [count,setCount] = useState(0)
  let [num,setNum] = useState(0)

  let callback = useCallback(()=>{
    console.log(count)
    return count;
  },[num])

  return (
    <>
    <h3>状态count:{count}</h3>
    <h3>状态num:{num}</h3>
    <h3>callback:{callback()}</h3>
    <Button onClick={()=>{setCount(count+1)}}>change-count</Button>
    <Button onClick={()=>{setNum(num+1)}}>change-num</Button>
    </>
  )

 }

reactDom.render(
  <>
  <h2>useContext</h2>
  <FatherContext></FatherContext>
  <p>_____________________________________________________________</p>
  <h2>useMemo</h2>
  <Memotest></Memotest>
  <p>_____________________________________________________________</p>
  <h3>useCallback</h3>
  {/*作用和useMemo类似useCallback缓存的是个函数，是个函数就能执行*/}
  <Callbacktest></Callbacktest>
  
  </>
,document.getElementById("root")
)